package com.yanlin.internalcommon.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import com.yanlin.internalcommon.constant.TokenConstant;
import com.yanlin.internalcommon.dto.TokenResult;

import java.util.*;

/**
 * <p>标题：JwtUtils</p>
 * <p>功能：令牌工具类</p>
 * <p>
 * 其他说明：
 * </p>
 * <p>审核：</p>
 * <p>重构：</p>
 * <p>创建日期：2025-06-06 16:03</p>
 *
 * @author yanlin
 */
public class JwtUtils {

    private static final String SIGN = "CPFmsb!@#$$";
    private static final String PHONE_KEY = "phone";
    private static final String IDENTITY_KEY = "identity";
    private static final String TOKEN_TYPE = "tokenType";
    private static final String TOKEN_TIME = "tokenTime";
    private static final int EXPIRATION_DATE = 1;

    /**
     * 令牌生成
     * @param phone
     * @param identity
     * @param tokenType
     * @return
     */
    public static String generateToken(String phone, String identity, String tokenType){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, EXPIRATION_DATE);
        Date time = calendar.getTime();
        Map<String, String> map = new HashMap<>();
        map.put(PHONE_KEY, phone);
        map.put(IDENTITY_KEY, identity);
        map.put(TOKEN_TYPE, tokenType);
        map.put(TOKEN_TIME, time.toString());
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v) -> {
            builder.withClaim(k, v);
        });
        return builder.sign(Algorithm.HMAC256(SIGN));
    }

    /**
     * 令牌解析
     * @param token
     * @return
     */
    public static TokenResult parseToken(String token) {
        Verification verification = JWT.require(Algorithm.HMAC256(SIGN));
        DecodedJWT verify = verification.build().verify(token);
        Claim phoneClaim = verify.getClaim(PHONE_KEY);
        Claim identityClaim = verify.getClaim(IDENTITY_KEY);
        TokenResult tokenResult = new TokenResult();
        // claim的toString（）方法 字符串带引号，asString（）方法不会带引号
        tokenResult.setPhone(phoneClaim.asString())
                .setIdentity(identityClaim.asString());
        return tokenResult;
    }

    /**
     * token检查,token是否异常
     * @param token
     * @return
     */
    public static TokenResult checkToken(String token) {
        TokenResult tokenResult = null;
        try {
            // 解析token
            tokenResult = JwtUtils.parseToken(token);
        } catch (Exception e) {

        }
        return tokenResult;
    }

    private static class InnerTest{

        public static void main(String[] args) {
            String encode = generateToken("17620036161", "1", "accessToken");
            System.out.println("encode = " + encode);
            TokenResult tokenResult = parseToken(encode);
            System.out.println("手机号 =  " + tokenResult.getPhone() + "用户标识 = " + tokenResult.getIdentity());

        }

    }
}